/******************************************************************************
 * @File name   :      UserPermFuncServiceImpl.java
 *
 * @Author      :      wujianxi
 *
 * @Date        :      2011-6-20
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * 2011-6-20 下午06:59:00        wujianxi     1.0            Initial Version
 * 2011-9-28 下午05:30:00        wangzhize     1.1     增加方法 validateDeleteRole，验证角色是否可被删除
 * 2011-10-26 下午07:12:34        Wu Jianxi       1.2         fix bug
 *****************************************************************************/
package com.cap.bts.framework.dm.userperm.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cap.bts.commonfunc.common.constant.errorcode.DMErrorCodes;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.service.impl.BaseServiceImpl;
import com.cap.bts.framework.dm.userperm.service.IUserPermFuncService;
import com.cap.bts.framework.usermgnt.dao.IFunctionDao;
import com.cap.bts.framework.usermgnt.dao.IRoleDao;
import com.cap.bts.framework.usermgnt.dao.IUserDao;
import com.cap.bts.framework.usermgnt.dao.IUserGroupRoleDao;
import com.cap.bts.framework.usermgnt.dao.IUserRoleDao;
import com.cap.bts.framework.usermgnt.dao.IUserUsrGrpDao;
import com.cap.bts.framework.usermgnt.domain.Function;
import com.cap.bts.framework.usermgnt.domain.Role;
import com.cap.bts.framework.usermgnt.domain.User;
import com.cap.bts.framework.usermgnt.domain.UserGroup;
import com.cap.bts.framework.usermgnt.domain.UserGroupFunction;
import com.cap.bts.framework.usermgnt.domain.UserGroupRole;
import com.cap.bts.framework.usermgnt.domain.UserRole;
import com.cap.bts.framework.usermgnt.dto.RoleAndFunctionsDto;
import com.cap.bts.framework.usermgnt.dto.UserUsrGrpResultDto;
import com.cap.bts.framework.usermgnt.service.IUserMgntService;


/**
 *
 */
@Transactional(rollbackFor = AppException.class)
@Service
public class UserPermFuncServiceImpl extends BaseServiceImpl implements IUserPermFuncService {

    @Resource(name = "userRoleDao")
    private IUserRoleDao userRoleDao;
    
    @Resource(name = "userGroupRoleDao")
    private IUserGroupRoleDao userGroupRoleDao;
    
    @Resource(name = "userDao")
    private IUserDao userDao;
    
    @Resource(name = "roleDao")
    private IRoleDao roleDao;
    
    @Autowired
    private IUserMgntService userMgntService;
    
    @Resource(name = "userUsrGrpDao")
    private IUserUsrGrpDao userUsrGrpDao;
    
    
    @Resource(name = "userPermFuncServiceImpl")
    private IUserPermFuncService userPermFuncService;
    
    @Resource(name = "functionDao")
    private IFunctionDao functionDao;
    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2011-6-20
     * @see com.cap.bts.gdms.dm.userperm.service.IUserPermFuncService#updateUserAndRoleRelation(com.cap.bts.framework.usermgnt.dto.AuthorizedUserResultDto)
    **/
    @Override
    public void updateUserAndRoleRelation(long userId, long roleId, int isDefaultRole) throws AppException {
        User user = userDao.findById(userId);
        Role role = roleDao.findById(roleId);
        
        UserRole userrole = new UserRole();
        userrole.setUser(user);
        userrole.setRole(role);
        userrole.setIsDefaultRole(isDefaultRole);
        userRoleDao.save(userrole);
    }
    
    /** 
     * overridden:
     * @Date        :      2011-6-30
    **/
    @Override
    public void deleteUserAndRoleRelation(long userId) throws AppException {
        // 根据用户id，删除数据
        List<UserRole> userRoleList = userRoleDao.getUserRoleExists(userId);
        for (UserRole ur : userRoleList) {
            userRoleDao.remove(ur);
        }
    }

    /** 
     * overridden:
     * @Date        :      2011-7-4
     * @see com.cap.bts.gdms.dm.userperm.service.IUserPermFuncService#transferWork(long, long, boolean)
    **/
    @Override
    public void transferWork(long fromUserId, long toUserId, boolean needTransfer)
        throws AppException {
        
    }

	/**
	 * {@inheritDoc} 
	 * overridden:
	 * @Date        :      2011-9-1
	 * @see com.cap.bts.gdms.dm.userperm.service.IUserPermFuncService#createRolesAndFunctions(com.cap.bts.framework.usermgnt.dto.RoleAndFunctionsDto)
	**/
	@Override
	public void createRolesAndFunctions(RoleAndFunctionsDto roleAndFunctionsDto)
			throws AppException {
		userMgntService.createRolesAndFunctions(roleAndFunctionsDto);
	}

	/**
	 * {@inheritDoc} 
	 * overridden:
	 * @Date        :      2011-9-1
	 * @see com.cap.bts.gdms.dm.userperm.service.IUserPermFuncService#updateRoleAndFunctions(com.cap.bts.framework.usermgnt.dto.RoleAndFunctionsDto)
	**/
	@Override
	public void updateRoleAndFunctions(RoleAndFunctionsDto roleAndFunctionsDto)
			throws AppException {
	}

	/**
	 * {@inheritDoc} 
	 * overridden:
	 * @Date        :      2011-9-1
	 * @see com.cap.bts.gdms.dm.userperm.service.IUserPermFuncService#deleteRoleById(java.lang.Long)
	**/
	@Override
	public boolean deleteRoleById(Long id) throws AppException {
		Role role = roleDao.findById(id);
		if (role!=null){
			userMgntService.deleteRoleById(id);
		}
		return true;		
	}

    /** 
     * overridden:
     * @Date        :      2011-9-6
     * @see com.cap.bts.gdms.dm.userperm.service.IUserPermFuncService#jmsUserAndRole(java.lang.Long, java.util.List)
    **/
    @Override
    public void jmsUserAndRole(Long userId, List<String> roleList) throws AppException {
    }

	/**
	 * {@inheritDoc} 
	 * overridden:
	 * @Date        :      2011-9-28
	 * @see com.cap.bts.gdms.dm.userperm.service.IUserPermFuncService#validateDeleteRole(java.lang.Long)
	**/
	@Override
	public boolean validateDeleteRole(Long roleId) throws AppException {
		List<UserRole> userRoles = userRoleDao.getUserRolesByRoleId(roleId);
		//如果有用户引用则返回
		if (userRoles!=null && userRoles.size()>0){
			return false;
		}
		List<UserGroupRole> userGroupRoles = userGroupRoleDao.getUserGroupRoleListByRoleId(roleId);
		//如果有组引用则返回
		if (userGroupRoles!=null && userGroupRoles.size()>0){
			return false;
		}
		return true;
			
	}

	/**
	 * {@inheritDoc} 
	 * overridden:
	 * @Date        :      2012-6-28
	 * @see com.cap.bts.gdms.dm.userperm.service.IUserPermFuncService#updateUserAndRoleRelation(java.lang.String[], long)
	**/
	@Override
	public void updateUserAndRoleRelation(String[] roleArray, long userId)
			throws AppException {
    	List<String> roleList = new ArrayList<String>();
   	 	// delete tr_user_role
    	userMgntService.deleteUserRolesByUserCode(userMgntService.getUserByUserId(userId).getUserCode());
    	User user = userDao.findById(userId);
		//通过userId查询对应的岗位
		List<UserUsrGrpResultDto> usrGrpList = this.userUsrGrpDao.getUserUsrGrpById(userId);
		//TODO MAKE STRONGER
		String strUsrGrpIn = "(";
		if (!usrGrpList.isEmpty()) {
			for (UserUsrGrpResultDto usrGrp : usrGrpList) {
				strUsrGrpIn += usrGrp.getUserGroupId() + ",";
			}
			strUsrGrpIn = strUsrGrpIn.substring(0, strUsrGrpIn.length() - 1);
		}else{
			strUsrGrpIn += "-1";
		}
		strUsrGrpIn += ")";
		if (null!=roleArray && roleArray.length > 0) {
			for (int i = 0; i < roleArray.length; i++) {
				if (!"-1".equals(roleArray[i])) {
					String[] roleAndFlag = roleArray[i].split(",");
					if (roleAndFlag != null && roleAndFlag.length == 2) { //默认角色,直接保存user-role关系
						long roleId = Long.valueOf(roleAndFlag[0]);
						int isDefaultRole = Integer.valueOf(roleAndFlag[1]);
						Role role = roleDao.findById(roleId);
						roleList.add(role.getRoleCode() + "," +isDefaultRole);
						userPermFuncService.updateUserAndRoleRelation(userId, roleId, isDefaultRole);
					} else if (roleAndFlag != null && roleAndFlag.length == 1) {
						long roleId = Long.valueOf(roleAndFlag[0]);
						Role role = roleDao.findById(roleId);
						// 检核角色对应功能权限是否合法
						List<UserGroupFunction> privateRoleFunctionsReturn = new ArrayList<UserGroupFunction>();
						if (!userMgntService.checkIsRightfulByUserGroupAndRoleId(
								strUsrGrpIn, roleId,user.getBrandId(), privateRoleFunctionsReturn)) {		
							String roleName = "";
							if(null != role){
								roleName=role.getRoleName();
							}
							List<String> param = new ArrayList<String>();
							StringBuilder privateFunctions=new StringBuilder();
							privateFunctions.append("(");
							for(int j=0;j<privateRoleFunctionsReturn.size();j++){
								UserGroupFunction userGroupFunction=privateRoleFunctionsReturn.get(j);
								UserGroup userGroup =userMgntService.getUserGroupById(userGroupFunction.getUserGroupId());
								Function  function=functionDao.findById(userGroupFunction.getFunctionId());
								if(null!=userGroup){
									privateFunctions.append(""+userGroup.getUserGroupName());
								}
								privateFunctions.append(":");
								if(null!=function){
									privateFunctions.append(""+function.getFunctionName());
								}
								privateFunctions.append(";");
							}
							privateFunctions.append(")");
							String error = "The role: " +roleName+ " contain private function!";
							AppException appException=new AppException(
									DMErrorCodes.DM_ROLE_HAVE_PRIVATE_FUNCTION, error);
							param.add(roleName);
							param.add(privateFunctions.toString());
							appException.setParam(param);
			                logger.error(error);
							throw appException;
						}
						int isDefaultRole = 0;
						roleList.add(role.getRoleCode() + "," +isDefaultRole);
						userPermFuncService.updateUserAndRoleRelation(userId, roleId, isDefaultRole);
					}
				}
			}
		}
		
   }

}
